using AutoMapper;
using Domain.Material_Management;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Material_Management;
using ReturnValue;
using Yitter.IdGenerator;

namespace MES.Server.API.Application.Handler.Material_Management
{
    public class AddChildBomHandler : IRequestHandler<AddChildBomCommand, ApiResult<int>>
    {
        private readonly IRepository<BomModel> bomRepo;
        private readonly IMapper mapper;

        public AddChildBomHandler(IRepository<BomModel> bomRepo, IMapper mapper)
        {
            this.bomRepo = bomRepo;
            this.mapper = mapper;
        }

        /// <summary>
        /// 添加子级BOM
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddChildBomCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            // 验证父级BOM是否存在
            var parentBom = bomRepo.GetAll().Where(a => a.Id == request.ParentBomId && !a.IsDel).FirstOrDefault();
            if (parentBom == null)
            {
                result.Code = StatusCode.Fail;
                result.Message = "父级BOM不存在！";
                return await Task.FromResult(result);
            }

            // 查找要添加为子级的BOM
            var childBom = bomRepo.GetAll().Where(a => a.BomCode == request.BomCode && !a.IsDel).FirstOrDefault();
            if (childBom == null)
            {
                // 如果子级BOM不存在，则创建新的BOM
                var model = mapper.Map<BomModel>(request);
                model.Id = YitIdHelper.NextId();
                model.CreateTime = DateTime.Now;
                model.IsDel = false;
                model.ParentId = request.ParentBomId;
                model.Level = parentBom.Level + 1;
                model.IsLeaf = true;

                // 更新父级的IsLeaf状态
                parentBom.IsLeaf = false;
                await bomRepo.UpdateAsync(parentBom);

                var affectedRows = await bomRepo.AddAsync(model);
                if (affectedRows > 0)
                {
                    result.Code = StatusCode.Success;
                    result.Message = "添加子级BOM成功！";
                    result.Data = affectedRows;
                }
                else
                {
                    result.Code = StatusCode.Fail;
                    result.Message = "添加子级BOM失败，数据库操作未成功！";
                    result.Data = 0;
                }
            }
            else
            {
                // 如果BOM已存在，则更新其父级关系
                childBom.ParentId = request.ParentBomId;
                childBom.Level = parentBom.Level + 1;
                childBom.UpdateTime = DateTime.Now;
                
                // 更新父级的IsLeaf状态
                parentBom.IsLeaf = false;
                await bomRepo.UpdateAsync(parentBom);
                
                var affectedRows = await bomRepo.UpdateAsync(childBom);
                if (affectedRows > 0)
                {
                    result.Code = StatusCode.Success;
                    result.Message = "设置BOM关系成功！";
                    result.Data = affectedRows;
                }
                else
                {
                    result.Code = StatusCode.Fail;
                    result.Message = "设置BOM关系失败，数据库操作未成功！";
                    result.Data = 0;
                }
            }
            
            return await Task.FromResult(result);
        }
    }
}